package control
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;

	/**
	 *键盘侦听类，并将键盘的状态UP,DOWN,LEFT,RIGHT返回给用户
	 * 
	 * 公共方法：KeyboardCtrl(up,down,left,right,bubble):void 设置自定义方向键和放泡键，默认为上下左右键
	 * 
	 * UP():Boolean 返回向上键是否按下
	 * DOWN():Boolean 返回向下键是否按下
	 * LEFT():Boolean 返回向左键是否按下
	 * RIGHT():Boolean 返回向右键是否按下
	 * BUBBLE():Boolean 返回放泡键是否按下
	 * 
	 * startKeyboardListen():void 开始侦听键盘
	 * stopKeyboardListen():void 停止键盘侦听
	 * @author Felix
	 * 
	 */	
	public class KeyboardCtrl extends Sprite
	{
		private var _up:uint = 0;
		private var _down:uint = 0;
		private var _left:uint = 0;
		private var _right:uint = 0;
		private var _space:uint = 0;
		
		private var isUp:Boolean = false;
		private var isDown:Boolean = false;
		private var isLeft:Boolean = false;
		private var isRight:Boolean = false;
		private var isSpace:Boolean = false;
		
		public function KeyboardCtrl(up:uint=38,down:uint=40,left:uint=37,right:uint=39,space:uint=32)
		{
			_up = up;
			_down = down;
			_left = left;
			_right = right;
			_space = space;
		}
		/**
		 * 在舞台添加KeyboardCtrl对象后开始侦听键盘事件
		 * 
		 */		
		public function startKeyboardListen():void
		{
			if (!stage) {
				addEventListener(Event.ADDED_TO_STAGE,onAddStage);
			} else {
				onAddStage(null);
			}
		}
		/**
		 *给舞台添加键盘按下和抬起的监听事件。 
		 * @param event
		 * 
		 */		
		protected function onAddStage(event:Event):void
		{
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
			stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
		}
		
		/**
		 * 移除按键侦听器
		 * 
		 */		
		public function stopKeyboardListen():void
		{
			stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDown);
			stage.removeEventListener(KeyboardEvent.KEY_UP,keyUp);
		}
		
		/**
		 * 侦听键盘方向键按下
		 * @param e
		 * 
		 */		
		private function keyDown(e:KeyboardEvent):void
		{
			switch(e.keyCode){
				case _left:
					isLeft = true;
					break;
				case _up:
					isUp = true;
					break;
				case _right:
					isRight = true;
					break;
				case _down:
					isDown = true;
					break;
				case _space:
					isSpace = true;
					break;
			}
		}
		
		/**
		 * 侦听键盘方向键抬起
		 * @param e
		 * 
		 */		
		private function keyUp(e:KeyboardEvent):void
		{
			switch(e.keyCode){
				case _left:
					isLeft = false;
					break;
				case _up:
					isUp = false;
					break;
				case _right:
					isRight = false;
					break;
				case _down:
					isDown = false;
					break;
				case _space:
					isSpace = false;
					break;
			}
		}
		
		public function get UP():Boolean
		{
			return isUp;
		}
		
		public function get DOWN():Boolean
		{
			return isDown;
		}
		
		public function get LEFT():Boolean
		{
			return isLeft;
		}
		
		public function get RIGHT():Boolean
		{
			return isRight;
		}
		
		public function get BUBBLE():Boolean
		{
			return isSpace;
		}
	}
}